<template>
  <div class="min-h-screen bg-gray-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900">题解</h1>
        <p class="text-gray-600">查看题目的详细解答和思路分析</p>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="md:col-span-2">
            <div class="relative">
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索题解..."
                class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                @input="handleSearch"
              />
              <svg class="absolute left-3 top-2.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
              </svg>
            </div>
          </div>

          <div>
            <select
              v-model="selectedDifficulty"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @change="handleFilter"
            >
              <option value="">所有难度</option>
              <option value="Easy">简单</option>
              <option value="Medium">中等</option>
              <option value="Hard">困难</option>
            </select>
          </div>

          <div>
            <select
              v-model="selectedLanguage"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @change="handleFilter"
            >
              <option value="">所有语言</option>
              <option value="javascript">JavaScript</option>
              <option value="python">Python</option>
              <option value="java">Java</option>
              <option value="cpp">C++</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 题解列表 -->
      <div class="space-y-6">
        <div
          v-for="solution in filteredSolutions"
          :key="solution.id"
          class="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow"
        >
          <div class="flex items-start justify-between mb-4">
            <div class="flex-1">
              <div class="flex items-center space-x-3 mb-2">
                <h3 class="text-lg font-semibold text-gray-900">{{ solution.questionTitle }}</h3>
                <span
                  :class="[
                    'px-2 py-1 rounded text-xs font-semibold',
                    solution.difficulty === 'Easy' ? 'bg-green-100 text-green-800' :
                    solution.difficulty === 'Medium' ? 'bg-yellow-100 text-yellow-800' :
                    'bg-red-100 text-red-800'
                  ]"
                >
                  {{ solution.difficulty === 'Easy' ? '简单' : solution.difficulty === 'Medium' ? '中等' : '困难' }}
                </span>
                <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded font-semibold">
                  {{ solution.language }}
                </span>
              </div>
              
              <p class="text-gray-600 mb-3">{{ solution.summary }}</p>
              
              <div class="flex items-center space-x-4 text-sm text-gray-500">
                <div class="flex items-center">
                  <img
                    :src="solution.author.avatar || 'https://picsum.photos/200'"
                    :alt="solution.author.username"
                    class="w-5 h-5 rounded-full mr-2"
                  />
                  <span>{{ solution.author.username }}</span>
                </div>
                <span>{{ formatDate(solution.createdAt) }}</span>
                <div class="flex items-center">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                  </svg>
                  <span>{{ solution.views }} 次查看</span>
                </div>
                <div class="flex items-center">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                  </svg>
                  <span>{{ solution.likes }} 点赞</span>
                </div>
              </div>
            </div>
            
            <div class="flex items-center space-x-2">
              <button
                class="text-blue-600 hover:text-blue-800 text-sm font-medium"
                @click="viewSolution(solution)"
              >
                查看详情
              </button>
              <button
                class="text-green-600 hover:text-green-800 text-sm font-medium"
                @click="likeSolution(solution)"
              >
                点赞
              </button>
            </div>
          </div>
          
          <!-- 代码预览 -->
          <div class="bg-gray-50 rounded-lg p-4 mb-4">
            <div class="flex items-center justify-between mb-2">
              <span class="text-sm font-medium text-gray-700">代码预览</span>
              <span class="text-xs text-gray-500">{{ solution.language }}</span>
            </div>
            <pre class="text-sm text-gray-800 overflow-x-auto"><code>{{ solution.codePreview }}</code></pre>
          </div>
          
          <!-- 标签 -->
          <div class="flex flex-wrap gap-2">
            <span
              v-for="tag in solution.tags"
              :key="tag"
              class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded"
            >
              {{ tag }}
            </span>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="mt-8 flex justify-center">
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
          <button
            :disabled="currentPage === 1"
            class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            @click="goToPage(currentPage - 1)"
          >
            上一页
          </button>
          <button
            v-for="page in visiblePages"
            :key="page"
            :class="[
              'relative inline-flex items-center px-4 py-2 border text-sm font-medium',
              page === currentPage
                ? 'z-10 bg-blue-50 border-blue-500 text-blue-600'
                : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'
            ]"
            @click="goToPage(page)"
          >
            {{ page }}
          </button>
          <button
            :disabled="currentPage === totalPages"
            class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            @click="goToPage(currentPage + 1)"
          >
            下一页
          </button>
        </nav>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredSolutions.length === 0" class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">暂无题解</h3>
        <p class="mt-1 text-sm text-gray-500">该筛选条件下没有找到题解</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

// 响应式数据
const searchQuery = ref('')
const selectedDifficulty = ref('')
const selectedLanguage = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 模拟题解数据
const solutions = ref([
  {
    id: 1,
    questionTitle: '两数之和',
    summary: '使用哈希表存储已遍历的元素，时间复杂度O(n)，空间复杂度O(n)',
    difficulty: 'Easy',
    language: 'JavaScript',
    author: {
      username: '算法大师',
      avatar: '/static/avatar/1.jpg'
    },
    views: 1250,
    likes: 89,
    createdAt: new Date('2023-01-15'),
    codePreview: `function twoSum(nums, target) {
    const map = new Map();
    
    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        
        if (map.has(complement)) {
            return [map.get(complement), i];
        }
        
        map.set(nums[i], i);
    }
    
    return [];
}`,
    tags: ['哈希表', '数组']
  },
  {
    id: 2,
    questionTitle: '无重复字符的最长子串',
    summary: '滑动窗口算法，使用双指针维护一个不包含重复字符的窗口',
    difficulty: 'Medium',
    language: 'Python',
    author: {
      username: '编程高手',
      avatar: null
    },
    views: 980,
    likes: 67,
    createdAt: new Date('2023-02-20'),
    codePreview: `def lengthOfLongestSubstring(s):
    char_set = set()
    left = 0
    max_length = 0
    
    for right in range(len(s)):
        while s[right] in char_set:
            char_set.remove(s[left])
            left += 1
        
        char_set.add(s[right])
        max_length = max(max_length, right - left + 1)
    
    return max_length`,
    tags: ['滑动窗口', '哈希表', '字符串']
  },
  {
    id: 3,
    questionTitle: '寻找两个正序数组的中位数',
    summary: '二分查找算法，在两个有序数组中寻找第k小的元素',
    difficulty: 'Hard',
    language: 'Java',
    author: {
      username: '代码达人',
      avatar: null
    },
    views: 750,
    likes: 45,
    createdAt: new Date('2023-03-10'),
    codePreview: `public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    int m = nums1.length;
    int n = nums2.length;
    int left = (m + n + 1) / 2;
    int right = (m + n + 2) / 2;
    
    return (findKth(nums1, 0, nums2, 0, left) + 
            findKth(nums1, 0, nums2, 0, right)) / 2.0;
}

private int findKth(int[] nums1, int i, int[] nums2, int j, int k) {
    // 二分查找实现
    // ...
}`,
    tags: ['二分查找', '数组', '分治']
  }
])

// 计算属性
const filteredSolutions = computed(() => {
  let filtered = solutions.value

  // 难度过滤
  if (selectedDifficulty.value) {
    filtered = filtered.filter(s => s.difficulty === selectedDifficulty.value)
  }

  // 语言过滤
  if (selectedLanguage.value) {
    filtered = filtered.filter(s => s.language.toLowerCase() === selectedLanguage.value)
  }

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(s =>
      s.questionTitle.toLowerCase().includes(query) ||
      s.summary.toLowerCase().includes(query) ||
      s.tags.some(tag => tag.toLowerCase().includes(query))
    )
  }

  return filtered
})

const totalSolutions = computed(() => filteredSolutions.value.length)
const totalPages = computed(() => Math.ceil(totalSolutions.value / pageSize.value))

const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

const viewSolution = (solution: any) => {
  console.log('查看题解:', solution)
  // 这里可以跳转到题解详情页面
}

const likeSolution = (solution: any) => {
  solution.likes++
  console.log('点赞题解:', solution)
}

onMounted(async () => {
  const userId = route.params.id
  try {
    // 这里加载题解数据
    console.log('加载题解数据:', userId)
  } catch (error) {
    console.error('加载题解数据失败:', error)
  }
})
</script>
